// 接口定义

use async_trait::async_trait;
use anyhow::Result as AnyhowResult;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::models::{DataSourceSchema, DataSourceType};

/// 数据源适配器接口
#[async_trait]
pub trait DataSourceAdapter: Send + Sync {
    /// 连接到数据源
    async fn connect(&self, data_source_type: &str, connection_string: &str)
        -> AnyhowResult<Box<dyn DataSourceConnection>>;

    /// 提取数据源Schema
    async fn extract_schema(&self, connection: &dyn DataSourceConnection) -> AnyhowResult<DataSourceSchema>;

    /// 测试连接
    async fn test_connection(&self, connection: &dyn DataSourceConnection) -> AnyhowResult<bool>;

    /// 获取支持的数据源类型
    fn get_supported_data_sources(&self) -> Vec<String>;
}

/// 数据源连接接口
#[async_trait]
pub trait DataSourceConnection: Send + Sync {
    /// 打开连接
    async fn open(&mut self) -> AnyhowResult<()>;

    /// 关闭连接
    async fn close(&mut self) -> AnyhowResult<()>;

    /// 检查连接状态
    fn is_connected(&self) -> bool;

    /// 查询数据
    async fn query_data(&self, query: &str) -> AnyhowResult<Vec<serde_json::Value>>;
}

/// 连接状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConnectionStatus {
    Connected,
    Disconnected,
    Connecting,
    Error(String),
}

/// Schema提取结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaExtractionResult {
    pub schema: DataSourceSchema,
    pub extraction_time: chrono::DateTime<chrono::Utc>,
    pub metadata: HashMap<String, serde_json::Value>,
}

/// 数据查询
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataQuery {
    pub query_type: QueryType,
    pub parameters: HashMap<String, serde_json::Value>,
    pub filters: Vec<QueryFilter>,
    pub limit: Option<u32>,
    pub offset: Option<u32>,
}

/// 查询类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum QueryType {
    Select,
    Insert,
    Update,
    Delete,
    Custom(String),
}

/// 查询过滤器
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryFilter {
    pub field: String,
    pub operator: FilterOperator,
    pub value: serde_json::Value,
}

/// 过滤器操作符
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FilterOperator {
    Equal,
    NotEqual,
    GreaterThan,
    GreaterThanOrEqual,
    LessThan,
    LessThanOrEqual,
    Like,
    In,
    NotIn,
    IsNull,
    IsNotNull,
}

/// 查询结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryResult {
    pub data: Vec<serde_json::Value>,
    pub total_count: u64,
    pub execution_time: u64,
    pub metadata: HashMap<String, serde_json::Value>,
}

/// 测试结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestResult {
    pub success: bool,
    pub message: String,
    pub details: Option<HashMap<String, serde_json::Value>>,
    pub execution_time: u64,
}